<script setup>
import CardComponent from "@/components/CardComponent.vue";
import { Delete, Plus, Edit, Search, Picture } from '@element-plus/icons-vue'

import { ref } from "vue";
import { manageGetAllCategory, manageGetAllFoods, manageQueryFoodLikeByNameOrCategoryIdOrStatus, manageDeleteFoodById, manageUpdateFoodStatusById, manageBatchDeleteFoods, manageGetFoodById, manageUpdateFoodById } from "@/api/manage";
import { formatOperateTime } from "@/utils/format";
import { ElMessageBox, ElMessage } from "element-plus";
const formValues = ref({
  name: '',
  categoryName: '',
  status: ''
})
// 存储菜品分类
const categoryList = ref(null)
const foodList = ref(null)
const getAllCategory = async () => {
  // const res = await manageGetAllCategory()
  // categoryList.value = res.result.map(item => item.name)
  // console.log(res);

  const { result } = await manageGetAllCategory()
  categoryList.value = result
  // console.log(categoryList.value);
}
const getAllFoods = async () => {
  const res = await manageGetAllFoods()
  // console.log(res);
  foodList.value = res.result
}
getAllCategory()
getAllFoods()

// 模糊查询food
const onSearchFood = async () => {

  const { result } = await manageQueryFoodLikeByNameOrCategoryIdOrStatus(formValues.value)
  foodList.value = result
}

// 删除food
const onDeleteFood = async (id) => {
  console.log(id);

  try {
    await ElMessageBox.confirm(
      "请问是否确定删除该菜品",
      "温馨提示",
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await manageDeleteFoodById({ id })
    ElMessage.success("删除成功")
    getAllFoods()
  } catch (e) {
    ElMessage.info('已取消删除')
  }
}
// 修改food状态
const onChangeStatus = async (id, status) => {
  if (status === 1) {
    await manageUpdateFoodStatusById({ id, status: 0 })

  } else {
    await manageUpdateFoodStatusById({ id, status: 1 })

  }
  getAllFoods()
}
// 批量删除
const tableRef = ref(null)
const batchDelete = async () => {
  // 获取选中的项
  const res = tableRef.value.getSelectionRows()
  // 过滤出ids
  const ids = res.map(item => item.id)
  if (ids === undefined || ids.length === 0) {
    return ElMessage.error("请选择要删除的菜品")
  }
  await manageBatchDeleteFoods(ids)
  getAllFoods()

}

// 修改菜品
const isShowDrawer = ref(false)
const changeFood = ref(
  {
    id: null,
    name: null,
    categoryId: null,
    price: null,
    imageUrl: null,
    description: null,
    flavorName: null,
    flavorValue: []
  }
)
const imageShow = ref(null)
const onChangeFood = async (id) => {
  isShowDrawer.value = true

  const { result } = await manageGetFoodById({ id })

  changeFood.value.id = id
  changeFood.value.name = result.name
  changeFood.value.categoryId = result.categoryId
  changeFood.value.price = result.price
  changeFood.value.description = result.description
  changeFood.value.image = result.image
  imageShow.value = result.image
  changeFood.value.flavorName = result.flavorName
  if (result.flavorValue) {
    // changeFood.value.flavorValue = JSON.parse(result.flavorValue.replace(/,/g, ',').replace(/([^[\],]+)/g, '"$1"'))
    changeFood.value.flavorValue = JSON.parse(result.flavorValue)
  }

}
// 图片更新
const beforeAvatarUpload = (file) => {

  imageShow.value = URL.createObjectURL(file.raw)
  changeFood.value.image = file.raw
}

// 提交修改
const onSubmitFood = (id) => {
  const newForm = new FormData()
  // 判断不为空才添加到FormData
  if (changeFood.value.id) {
    newForm.append('id', changeFood.value.id)
  }
  if (changeFood.value.name) {
    newForm.append('name', changeFood.value.name)
  }
  if (changeFood.value.categoryId) {
    newForm.append('categoryId', changeFood.value.categoryId)
  }
  if (changeFood.value.price) {
    newForm.append('price', changeFood.value.price)
  }
  if (changeFood.value.description) {
    newForm.append('description', changeFood.value.description)
  }
  if (changeFood.value.image) {
    newForm.append('imageUrl', changeFood.value.image)
  }
  if (changeFood.value.flavorName) {
    newForm.append('flavorName', changeFood.value.flavorName)
  }
  if (changeFood.value.flavorValue) {
    newForm.append('flavorValue', JSON.stringify(changeFood.value.flavorValue))
  }
  const isRepeat = foodList.value.some(item => item.name === changeFood.value.name && item.id !== id)
  if (isRepeat) return ElMessage.error("菜品名称重复")
  manageUpdateFoodById(newForm)
  changeFood.value = {
    id: null,
    name: null,
    categoryId: null,
    price: null,
    imageUrl: null,
    description: null,
    flavorName: null,
    flavorValue: []
  }
  isShowDrawer.value = false
  ElMessage.success("修改成功")
  getAllFoods()
}
</script>

<template>
  <div>
    <CardComponent :is-need-head=false card-height="500px">
      <div class="food-header">
        <div>
          <el-form :inline="true" :model="formValues">
            <el-form-item label="菜品名称:">
              <el-input placeholder="请填写菜品名称" v-model="formValues.name"></el-input>
            </el-form-item>
            <el-form-item label="菜品分类:">
              <el-select clearable v-model="formValues.categoryName" placeholder="请选择" class="custom-food-name-select">
                <el-option v-for="(item, index) in categoryList" :key="index" :label=item.name
                  :value=item.id></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="售卖状态:">
              <el-select clearable v-model="formValues.status" placeholder="请选择" class="custom-food-name-select">
                <el-option label="启售" value="1"></el-option>
                <el-option label="停售" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item><el-button type="primary" @click="onSearchFood">查询</el-button></el-form-item>
          </el-form>
        </div>
        <div>
          <el-button type="danger" :icon="Delete" @click="batchDelete">批量删除</el-button>
          <el-button type="warning" :icon="Plus" @click="$router.push('/addFood')">新建菜品</el-button>
        </div>
      </div>
      <div>
        <el-table :data="foodList" style="width: 100%;" ref="tableRef">
          <el-table-column type="selection" width="40"></el-table-column>
          <el-table-column label="菜品名称" width="140" prop="name"></el-table-column>
          <el-table-column label="图片" width="140">
            <template #default="{ row }">
              <el-image style="width: 30px; height: 30px;" :src="row.image || 'invalid-image-url'" fit="cover"
                :preview-src-list="[row.image]" :z-index="999" :preview-teleported="true">
                <template #error>
                  <div class="image-viewer-slot image-slot">
                    <el-icon :size="30">
                      <Picture />
                    </el-icon>
                  </div>
                </template>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="菜品分类" width="140" prop="categoryName"></el-table-column>
          <el-table-column label="售价" width="140">
            <template #default="{ row }">
              {{ `￥${row.price}` }}
            </template>
          </el-table-column>
          <el-table-column label="售卖状态" width="140">
            <template #default="{ row }">
              {{ row.status === 1 ? "在售" : "停售" }}
            </template>
          </el-table-column>
          <el-table-column label="最后操作时间" width="140">
            <template #default="{ row }">
              {{ formatOperateTime(row.updateTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" class-name="operation-column">
            <template #default="{ row }">
              <el-button type="primary" :icon="Search" @click="onChangeFood(row.id)">修改</el-button>
              <el-button type="danger" :icon="Delete" @click="onDeleteFood(row.id)">删除</el-button>
              <el-button type="warning" :icon="Edit" v-if="row.status === 1"
                @click="onChangeStatus(row.id, row.status)">停售</el-button>
              <el-button type="success" :icon="Edit" v-else @click="onChangeStatus(row.id, row.status)">起售</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </CardComponent>
    <!-- 抽屉组件 -->
    <div>
      <el-drawer v-model="isShowDrawer" size="50%">
        <template #header>
          <span>修改菜品信息</span>
        </template>
        <template #default>
          <el-form :model="changeFood">
            <el-form-item label="菜品名称:">
              <el-input v-model="changeFood.name"></el-input>
            </el-form-item>
            <el-form-item label="菜品分类:">
              <el-select placeholder="请选择" v-model="changeFood.categoryId">
                <el-option v-for="(value, index) in categoryList" :key="index" :value=value.id
                  :label="value.name"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="菜品价格:">
              <el-input v-model="changeFood.price"></el-input>
            </el-form-item>
            <el-form-item label="口味做法配置:">
              <CardComponent card-height="100px" card-width="100%">
                <div>口味名</div>
                <div class="config-item">
                  <div><el-input v-model="changeFood.flavorName"></el-input></div>
                  <div><el-input-tag v-model="changeFood.flavorValue"></el-input-tag></div>
                </div>
              </CardComponent>
            </el-form-item>
            <el-form-item label="菜品图片:">
              <el-upload class="avatar-uploader" :show-file-list="false" :on-change="beforeAvatarUpload"
                :auto-upload="false">
                <img v-if="imageShow" :src=imageShow class="avatar">
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="菜品描述">
              <el-input type="textarea" autosize style="width: 100%;" v-model="changeFood.description"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmitFood(changeFood.id)">保存</el-button>
              <el-button @click="isShowDrawer = false">取消</el-button>
            </el-form-item>
          </el-form>
        </template>
      </el-drawer>
    </div>
  </div>
</template>

<style scoped>
.food-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.custom-food-name-select .el-select__wrapper) {
  width: 120px;
}

:deep(.el-form-item) {
  margin: 0 10px;
}

:deep(.el-input__wrapper) {
  width: 120px;
}



/* 操作列的按钮排版 */
:deep(.operation-column .cell) {
  display: flex;
  gap: 8px;
  /* 可选：增加按钮间距，让排版更美观 */
}

:deep(.operation-column .cell .el-button) {
  width: 60px;
}

:deep(.el-table__header-wrapper .operation-column) {
  text-align: center;
}

:deep(thead .operation-column .cell) {
  justify-content: center;
}

:deep(.el-drawer__body .el-form-item) {
  margin: 18px 0;
}

.config-item {
  display: flex;
  align-items: flex-end;
  gap: 10px;
}

:deep(.el-drawer__body .el-input-tag) {
  width: 400px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
